package org.spring.qq_chat_java.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.spring.qq_chat_java.constant.ReceiverType;
import org.spring.qq_chat_java.pojo.Message;
import org.spring.qq_chat_java.pojo.Result;
import org.spring.qq_chat_java.pojo.uto.chatUTO;
import org.spring.qq_chat_java.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/messages")
@CrossOrigin(origins = "*")
@RequiredArgsConstructor
public class MessageController {

    private final MessageService messageService;

    //  添加
    @PostMapping("/add")
    public Result<Message> add(@RequestBody Message message){
        messageService.save(message);
        //查询该数据库中的message
        Message msg=messageService.getById(message.getMessageId());
        return msg != null ? Result.success(msg) : Result.error("添加失败");
    }

    //查询聊天信息(通过senderId和receiverId查询)
    @PostMapping
    public Result<List<Message>> getMessage(@RequestBody chatUTO chatUTO){
        System.out.println(chatUTO);
        //如果是私聊
        if(chatUTO.getReceiverType()== ReceiverType.user){
        List<Message> msg1=messageService.list(new QueryWrapper<Message>()
                .eq("sender_id",chatUTO.getSenderId())
                .eq("receiver_id",chatUTO.getReceiverId())
                .eq("receiver_type",chatUTO.getReceiverType()));
        List<Message> msg2=messageService.list(new QueryWrapper<Message>()
                .eq("sender_id",chatUTO.getReceiverId())
                .eq("receiver_id",chatUTO.getSenderId())
                .eq("receiver_type",chatUTO.getReceiverType()));

        msg1.addAll(msg2);
        //按字段时间排序sentTime
        msg1.sort(Comparator.comparing(Message::getSentTime));


         return Result.success(msg1);
        }
        //如果是群聊：根据receiverId
        List<Message> msg2=messageService.list(new QueryWrapper<Message>()
                .eq("receiver_id",chatUTO.getReceiverId())
                .eq("receiver_type",chatUTO.getReceiverType()));
        return Result.success(msg2);



    }





}





























